package com.wdh.kjs.fragment;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.Adapter.InvestmentListAdapter;
import com.wdh.kjs.Adapter.ListViewForScrollView;
import com.wdh.kjs.R;
import com.wdh.kjs.activity.InvestmentDetailActivity;
import com.wdh.kjs.activity.ScreeningActivity;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.FilterRule;
import com.wdh.kjs.model.Filters;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.util.DateUtils;
import com.wdh.kjs.util.ToastUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by codingWw on 2016/3/7.
 */
public class InvestmentFragment extends Fragment implements View.OnClickListener{
    private PullToRefreshListView investment_listview;
    private ScrollView investment_scrollview;
    private InvestmentListAdapter investmentListAdapter;
    private List<HashMap<String, String>> datas;

    private Intent intent;
    private ImageView screening;
    private JsonModel jsonModel;
    private Filters filters;
    public static int totalrecords = 0;
    public static boolean mLoading = true;
    public static int page ;
    public static int rows = 3;
    public static int myrows = 3;
    private String statu;
    private String project_statue;
    private String project_style;
    private String project_data_low;
    private String project_data_high;
    private String benefitRate_row;
    private String benefitRate_high;
    private TextView sort_itemPushFlag;
    private TextView sort_gdAnnualizedBenefitRate;
    private TextView sort_interestDays;
    private String sordid;
    private String sord;
    private Boolean isChanged=true;
    private TextView tv_isnull;
    private int statues=0;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_investment, container, false);
        initView(view);
        initwidge();
        intweb();
        return view;
    }

    private void intweb() {
        RequestParams params = new RequestParams();
        page=1;
        params.addBodyParameter("page", page+"");
        params.addBodyParameter("rows", rows + "");
        params.addBodyParameter("sordid", "id");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_Invest_SEARCH, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();

                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                totalrecords = jsonModel.getTotalrecords();
                if (jsonModel.success) {

                    item();
                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(getActivity(), "网络异常！");
            }
        });

    }

    private void item() {
        investmentListAdapter = new InvestmentListAdapter(getActivity(), initListViewData());
        investment_listview.setAdapter(investmentListAdapter);

        investment_listview.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        investment_listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            // 下拉Pulling Down
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 下拉的时候数据重置
            }

            // 上拉Pulling Up
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 上拉的时候添加选项

                String label = DateUtils.formatDateTime(getActivity().getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);


                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                new GetDataTask().execute();


            }

        });
    }

    private class GetDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (totalrecords > datas.size()) {

                page += 1;
                myrows+=3;
                try {
                    getMoreList();

                } catch (Exception e) {
                    page -= 1;
                    myrows-=3;
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            if (mLoading == false)
                ToastUtils.showShort(getActivity(), "已无更多数据！");
            investment_listview.onRefreshComplete();

            super.onPostExecute(aVoid);

        }
    }

    private void getMoreList() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("page", page+"");
        params.addBodyParameter("rows", rows+"");
        if (statues==1){
            params.addBodyParameter("filter", JSON.toJSONString(filters));
        }
        params.addBodyParameter("sordid", "id");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_Invest_SEARCH, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                totalrecords = jsonModel.getTotalrecords();
                if (jsonModel.success) {
                    getMore();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(getActivity(), "网络异常！");
            }
        });

    }

    private void getMore() {
        for (int i = 0; i < jsonModel.getItems().size(); i++) {
            DecimalFormat df = new DecimalFormat("0.00");
            BigDecimal remain = new BigDecimal(jsonModel.getItems().get(i).getTargetMoney().toString()).subtract(new BigDecimal(jsonModel.getItems().get(i).getRaiseMoney().toString()));
            BigDecimal percent = new BigDecimal(jsonModel.getItems().get(i).getRaiseMoney().toString()).divide(jsonModel.getItems().get(i).getTargetMoney(),4,RoundingMode.HALF_UP).multiply(new BigDecimal(100 + ""));
//            BigDecimal percent=new BigDecimal(jsonModel.getItems().get(i).getRaiseMoney().toString()).divide(new BigDecimal(jsonModel.getItems().get(i).getTargetMoney().toString())).multiply(new BigDecimal(100 + ""));
//            int rate1 = new BigDecimal(percent + "").multiply(new BigDecimal(100 + "")).intValue();
            BigDecimal tate2=new BigDecimal(jsonModel.getItems().get(i).getGdAnnualizedBenefitRate() + "").multiply(new BigDecimal(100 + "")).setScale(2, BigDecimal.ROUND_HALF_UP);
            BigDecimal rate1 = new BigDecimal(percent + "").multiply(new BigDecimal(100 + "")).setScale(2, RoundingMode.HALF_UP);
            String  newrate1=df.format(percent);
            // int tate2 = new BigDecimal(jsonModel.getItems().get(i).getGdAnnualizedBenefitRate() + "").multiply(new BigDecimal(100 + "")).intValue();
//            switch (jsonModel.getItems().get(i).getItemStatus()){
//                case 7:
//                    statu = "抢购";
//                    break;
//                case 8:
//                    statu = "预热中";
//                    break;
//                case 9:
//                    statu = "抢购完成";
//                    break;
//                default:
//                    break;
//            }

            if(jsonModel.getItems().get(i).getItemStatus()==7){
                statu = "抢购";
            }else if(jsonModel.getItems().get(i).getItemStatus()==8){
                statu = "预热中";
            }else if(jsonModel.getItems().get(i).getItemStatus()==9 &&jsonModel.getItems().get(i).getGdBenefitReturnStep().equals("还款中")){
                statu = "还款中";
            }else if(jsonModel.getItems().get(i).getItemStatus()==9 &&jsonModel.getItems().get(i).getGdBenefitReturnStep().equals("还款完成")){
                statu = "还款完成";
            }else if(jsonModel.getItems().get(i).getItemStatus()==9 &&jsonModel.getItems().get(i).getGdBenefitReturnStep().equals("募集成功")){
                statu = "募集成功";
            }else if(jsonModel.getItems().get(i).getItemStatus()==10 ){
                statu = "坏账";
            }
            HashMap<String, String> hashMap = new HashMap<>();
            BigDecimal bigDecimal =new BigDecimal(jsonModel.getItems().get(i).getTargetMoney()+"").setScale(2,RoundingMode.HALF_UP);
            hashMap.put("tv_investment_name", jsonModel.getItems().get(i).getItemName());
            hashMap.put("tv_investment_available_amount",  "￥"+ remain+"元");
            hashMap.put("item_investment_scale", tate2 + "%");
            hashMap.put("item_investment_month",jsonModel.getItems().get(i).getInterestDays() + "天");
            hashMap.put("item_investment_financing_amount", "￥" + bigDecimal + "");
            hashMap.put("item_investment_state", statu);
            hashMap.put("percent", newrate1+"");
            hashMap.put("loadId", jsonModel.getItems().get(i).getItemId()+"");
            hashMap.put("status", jsonModel.getItems().get(i).getGdBenefitReturnStep());
            datas.add(hashMap);
        }

        if (datas.size() == totalrecords)
            mLoading = false;
        investmentListAdapter.notifyDataSetChanged();

    }

    private void initView(View view) {
        tv_isnull = (TextView) view.findViewById(R.id.tv_isnull);
        investment_listview = (PullToRefreshListView) view.findViewById(R.id.fragment_investment_listview);
        screening = (ImageView) view.findViewById(R.id.screening);
        sort_itemPushFlag = (TextView) view.findViewById(R.id.sort_itemPushFlag);
        sort_gdAnnualizedBenefitRate = (TextView) view.findViewById(R.id.sort_gdAnnualizedBenefitRate);
        sort_interestDays = (TextView) view.findViewById(R.id.sort_interestDays);
        sort_itemPushFlag.setOnClickListener(this);

    }

    private void initwidge() {

//        investment_listview.setOnItemClickListener(this);
        sort_gdAnnualizedBenefitRate.setOnClickListener(this);
        sort_interestDays.setOnClickListener(this);
        screening.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(view.getId()==R.id.screening){
                    intent = new Intent(getActivity(),ScreeningActivity.class);
//                    startActivity(intent);
                    startActivityForResult(intent,0);
                }
            }
        });
    }

    private List<HashMap<String, String>> initListViewData() {
        datas = new ArrayList<>();
        for (int i = 0; i < jsonModel.getItems().size(); i++) {
            DecimalFormat df = new DecimalFormat("0.00");
            BigDecimal remain = new BigDecimal(jsonModel.getItems().get(i).getTargetMoney().toString()).subtract(new BigDecimal(jsonModel.getItems().get(i).getRaiseMoney().toString())).setScale(2, RoundingMode.HALF_UP);
//            BigDecimal percent=new BigDecimal(jsonModel.getItems().get(i).getRaiseMoney().toString()).divide(new BigDecimal(jsonModel.getItems().get(i).getTargetMoney().toString())).multiply(new BigDecimal(100 + ""));
            BigDecimal percent = new BigDecimal(jsonModel.getItems().get(i).getRaiseMoney().toString()).divide(jsonModel.getItems().get(i).getTargetMoney(),4,RoundingMode.HALF_UP).multiply(new BigDecimal(100 + ""));
            BigDecimal rate1 = new BigDecimal(percent + "").multiply(new BigDecimal(100 + ""));
            String  newrate1=df.format(percent);
        //    int tate2 = new BigDecimal(jsonModel.getItems().get(i).getGdAnnualizedBenefitRate() + "").multiply(new BigDecimal(100 + "")).intValue();
            BigDecimal tate2=new BigDecimal(jsonModel.getItems().get(i).getGdAnnualizedBenefitRate() + "").multiply(new BigDecimal(100 + "")).setScale(2, BigDecimal.ROUND_HALF_UP);
//            switch (jsonModel.getItems().get(i).getItemStatus()){
//                case 7:
//                    statu = "抢购";
//                    break;
//                case 8:
//                    statu = "预热中";
//                    break;
//                case 9:
//                    statu = "抢购完成";
//                    break;
//                case 10:
//                    statu = "募集失败";
//                    break;
//            }
            if(jsonModel.getItems().get(i).getItemStatus()==7){
                statu = "抢购";
            }else if(jsonModel.getItems().get(i).getItemStatus()==8){
                statu = "预热中";
            }else if(jsonModel.getItems().get(i).getItemStatus()==9 &&jsonModel.getItems().get(i).getGdBenefitReturnStep().equals("还款中")){
                statu = "还款中";
            }else if(jsonModel.getItems().get(i).getItemStatus()==9 &&jsonModel.getItems().get(i).getGdBenefitReturnStep().equals("还款完成")){
                statu = "还款完成";
            }else if(jsonModel.getItems().get(i).getItemStatus()==9 &&jsonModel.getItems().get(i).getGdBenefitReturnStep().equals("募集成功")){
                statu = "募集成功";
            }else if(jsonModel.getItems().get(i).getItemStatus()==10 ){
                statu = "坏账";
            }
            BigDecimal mybigDecimal =new BigDecimal(jsonModel.getItems().get(i).getTargetMoney()+"").setScale(2,RoundingMode.HALF_UP);
            HashMap<String, String> hashMap = new HashMap<>();
//            hashMap.put("tv_investment_type", jsonModel.getItems().get(i).getItemName());
            hashMap.put("tv_investment_name", jsonModel.getItems().get(i).getItemName());
            hashMap.put("tv_investment_available_amount",  "￥"+ remain+"元");
            hashMap.put("item_investment_scale", tate2 + "%");
            hashMap.put("item_investment_month", jsonModel.getItems().get(i).getInterestDays() + "天");
            hashMap.put("item_investment_financing_amount", "￥" + mybigDecimal+ "");
            hashMap.put("item_investment_state", statu);
            hashMap.put("percent", newrate1+"");
            hashMap.put("loadId", jsonModel.getItems().get(i).getItemId()+"");
            hashMap.put("status", jsonModel.getItems().get(i).getGdBenefitReturnStep());

            datas.add(hashMap);
        }

        return datas;

    }




    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case 0:
                Bundle bundle=data.getBundleExtra("name");
                 project_statue = bundle.getString("project_statue");
                project_style = bundle.getString("project_style");
                project_data_low = bundle.getString("project_data_low");
                project_data_high = bundle.getString("project_data_high");
                benefitRate_row = bundle.getString("benefitRate_row");
                benefitRate_high = bundle.getString("benefitRate_high");
                conditionweb();
                break;
            default:
                break;
        }
    }

    private void conditionweb() {
        filters = new Filters();
        filters.addRules(new FilterRule("itemStatus", "et", project_statue));
        filters.addRules(new FilterRule("itemDays", "get", project_data_low));
        filters.addRules(new FilterRule("itemDays", "let", project_data_high));
        filters.addRules(new FilterRule("benefitRate", "get", benefitRate_row));
        filters.addRules(new FilterRule("benefitRate", "let", benefitRate_high));
        filters.addRules(new FilterRule("gdItemType", "et", project_style));

        Log.i("msg",project_statue+" "+project_data_low+" "+project_data_high+ " "+benefitRate_row+" "
        +benefitRate_high+" "+project_style);

        RequestParams params = new RequestParams();
        page=1;
        params.addBodyParameter("page", page+"");
        params.addBodyParameter("rows", rows + "");
        params.addBodyParameter("sordid", "id");
        params.addBodyParameter("filter", JSON.toJSONString(filters));
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_Invest_SEARCH, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                Log.i("msg","132 "+responseInfo.result);
                totalrecords = jsonModel.getTotalrecords();
                if (jsonModel.success) {
if (jsonModel.getItems().isEmpty()) {
    tv_isnull.setVisibility(View.VISIBLE);
    investment_listview.setVisibility(View.GONE);
}
                    else{
    statues=1;
                    item();}
                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(getActivity(), "网络异常！");
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.sort_itemPushFlag:
                sordid="itemStartDate";
                change();
                sorting();
                sort_itemPushFlag.setTextColor(getResources().getColor(R.color.colorPrimary));
                sort_gdAnnualizedBenefitRate.setTextColor(getResources().getColor(R.color.font_gray_dark));
                sort_interestDays.setTextColor(getResources().getColor(R.color.font_gray_dark));
                ToastUtils.showShort(getActivity(),"最新上线  "+sord);
                break;
            case R.id.sort_gdAnnualizedBenefitRate:
                sordid="gdAnnualizedBenefitRate";
                change();
                sorting();
                sort_itemPushFlag.setTextColor(getResources().getColor(R.color.font_gray_dark));
                sort_gdAnnualizedBenefitRate.setTextColor(getResources().getColor(R.color.colorPrimary));
                sort_interestDays.setTextColor(getResources().getColor(R.color.font_gray_dark));
                ToastUtils.showShort(getActivity(),"年化收益率  "+sord);
                break;
            case R.id.sort_interestDays:
                sordid="interestDays";
                change();
                sorting();
                sort_itemPushFlag.setTextColor(getResources().getColor(R.color.font_gray_dark));
                sort_gdAnnualizedBenefitRate.setTextColor(getResources().getColor(R.color.font_gray_dark));
                sort_interestDays.setTextColor(getResources().getColor(R.color.colorPrimary));
                ToastUtils.showShort(getActivity(),"项目期限  "+sord);
                break;
            default:
                break;
        }
    }

    private void sorting() {
        RequestParams params = new RequestParams();
        page=1;
        params.addBodyParameter("page", 1+"");
        params.addBodyParameter("rows", myrows + "");
        params.addBodyParameter("sordid", sordid);
        params.addBodyParameter("sord", sord);
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_Invest_SEARCH, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                if (jsonModel.success) {

                    item();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(getActivity(), "网络异常！");
            }
        });
    }

    public void change(){
        if(isChanged){
            sord="ASC";
        }else {
            sord="DESC";
        }
        isChanged=!isChanged;
    }
}
